//
//  EditProductViewController.m
//  quickBatchManager
//
//  Created by 王定波 on 15/9/30.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "EditProductViewController.h"

@interface EditProductViewController ()<UITextFieldDelegate>
{
    UIPopoverController *popover;
    NSArray *colorList;
    NSArray *sizeList;
    UIButton *singelBtn;
    UIButton *mulBtn;
    UIView *maintableView;
    UILabel *totalLabel;
    NSString *picpath;
    int scpos;
    CategoryModel *category;
}

@end

@implementation EditProductViewController
@synthesize product;


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(void)initUI
{
    UIImage *image = _bgImage.image;
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
    _bgImage.image=image;
    [self.view setBackgroundColor:[UIColor clearColor]];
    
    
    [_close bk_whenTapped:^{
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [_closeBtn bk_whenTapped:^{
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [self initAddUI];
    [self reloadUI];
}


-(void)initData
{
    picpath=@"";
    
}

-(void)initAddUI
{
    _photoImageView.hidden=YES;
    [_closeBtn bk_whenTapped:^{
        [self back];
    }];
    
    [_photoBtn bk_whenTapped:^{
        [self pickPhoto];
    }];
    
    [_cameraBtn bk_whenTapped:^{
        [self pickCamera];
    }];
    
    
    [_categoryBtn bk_whenTapped:^{
        ChooseCategoryController *menuVc=[[ChooseCategoryController alloc]init];
        menuVc.delegate=self;
        popover=[[UIPopoverController alloc]initWithContentViewController:menuVc];
        popover.popoverContentSize=CGSizeMake(200, 300);
        [popover presentPopoverFromRect:CGRectMake(40, 20, 10, 10) inView:_categoryBtn permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }];
    
    
    [_addBtn bk_whenTapped:^{
        if([_categoryBtn.titleLabel.text isEqualToString:@"选择分类"])
        {
            [self showAlert:@"请设置分类"];
            return ;
        }
        
        
        if([_modelNumberField.text isBlank])
        {
            [self showAlert:@"型号必须填写"];
            return ;
        }
        
        if([_inPriceField.text isBlank])
        {
            [self showAlert:@"进价必须填写"];
            return ;
        }
        
        if([_outPriceField.text isBlank])
        {
            [self showAlert:@"售价必须填写"];
            return ;
        }
        
        if(sizeList.count==0)
        {
            [self showAlert:@"尺码必须填写"];
            return ;
        }
        
        if(colorList.count==0)
        {
            [self showAlert:@"颜色必须填写"];
            return ;
        }
        
        
        if(![_colorSizeView checkInput:YES])
        {
            [self showAlert:@"数量必须填写"];
            return ;
        }
        
        [AppService editProductById:product.productId andModel:_editModelField.text andCategory:category andBuyPrice:_inPriceField.text andSalePrice:_outPriceField.text andImage:_photoImageView.image andPicPath:picpath andColorSizeView:_colorSizeView];
        
        [self showAlert:@"修改成功" handler:^{
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    }];
    
    
    
}


-(void) reloadUI
{
    
    AFTER_MAIN(0.1, ^{
        NSDictionary *dic=[AppService getSizeAndColorByModel:product.modelNo];
        
        [self didSelectDatas:ChooseTypeColor andData:[dic objectForKey:@"color"]];
        [self didSelectDatas:ChooseTypeSize andData:[dic objectForKey:@"size"]];
        
        
        _modelNumberField.text=product.modelNo;
        if(![product.photo isBlank])
        {
            _photoImageView.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:[ToolUtils getImageLocalPath:product.photo]]];
            _photoImageView.hidden=NO;
            picpath=product.photo;
        }
        
        _inPriceField.text=[ToolUtils priceToStr:product.buyPrice];
        _outPriceField.text=[ToolUtils priceToStr:product.salePrice];
        [_categoryBtn setTitle:product.category.categoryName forState:UIControlStateNormal];
    });
    
    
}



- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [super imagePickerController:picker didFinishPickingMediaWithInfo:info];
    _photoImageView.hidden=NO;
    UIImage * photo =[ToolUtils scaleToSize:(UIImage*)[info objectForKey:UIImagePickerControllerOriginalImage]];
    _photoImageView.image=photo;
    picpath=@"";
    
}



#pragma -ChooseDelegate
-(void)didSelectDatas:(ChooseType)type andData:(NSArray *)selectDatas
{
    UIColor *bg=[UIColor colorWithWhite:0.89 alpha:1];
    UIColor *textcolor=[UIColor colorWithWhite:0.49 alpha:1];
    UIColor *bordercolor=[UIColor colorWithRed:0.73 green:0.68 blue:0.69 alpha:1];
    switch (type) {
        case ChooseTypeSize:
            for (UIView *view in _sizeView.subviews) {
                [view removeFromSuperview];
            }
            int sy=0;
            int i=0;
            for (NSString *size in selectDatas) {
                UILabel *sizeLabel=[[UILabel alloc] initWithFrame:CGRectMake(sy, 5, 20, 30)];
                sizeLabel.text=size;
                sizeLabel.textAlignment=NSTextAlignmentCenter;
                sizeLabel.font=[UIFont systemFontOfSize:15];
                sizeLabel.textColor=textcolor;
                sizeLabel.backgroundColor=bg;
                sizeLabel.layer.cornerRadius=4;
                sizeLabel.clipsToBounds=YES;
                sizeLabel.layer.borderWidth=1;
                sizeLabel.layer.borderColor=bordercolor.CGColor;
                [sizeLabel sizeToFit];
                sizeLabel.frame=CGRectMake(sy, 5, sizeLabel.frame.size.width+10, 30);
                sy=CGRectGetMaxX(sizeLabel.frame)+10;
                
                
                sizeLabel.userInteractionEnabled=YES;
                
                [sizeLabel bk_whenTapped:^{
                    scpos=i;
                    AddSizeViewController *vc=[[AddSizeViewController alloc] init];
                    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                    vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
                    self.definesPresentationContext = YES;
                    vc.delegate=self;
                    vc.isRadios=YES;
                    vc.selectList=sizeList;
                    [self presentViewController:vc animated:YES completion:nil];
                }];
                
                
                
                i++;
                [_sizeView addSubview:sizeLabel];
            }
            
            
            for (NSLayoutConstraint *ct in  [_sizeView constraints]) {
                if(ct.firstAttribute==NSLayoutAttributeWidth)
                {
                    ct.constant=sy;
                }
            }
            sizeList=selectDatas;
            
            [self reloadNumber];
            break;
        case ChooseTypeColor:
            for (UIView *view in _colorView.subviews) {
                [view removeFromSuperview];
            }
            int cy=0;
            int j=0;
            for (NSString *size in selectDatas) {
                UILabel *sizeLabel=[[UILabel alloc] initWithFrame:CGRectMake(cy, 5, 20, 30)];
                sizeLabel.text=size;
                sizeLabel.textAlignment=NSTextAlignmentCenter;
                sizeLabel.font=[UIFont systemFontOfSize:15];
                sizeLabel.textColor=textcolor;
                sizeLabel.backgroundColor=bg;
                sizeLabel.layer.cornerRadius=4;
                sizeLabel.clipsToBounds=YES;
                sizeLabel.layer.borderWidth=1;
                sizeLabel.layer.borderColor=bordercolor.CGColor;
                sizeLabel.userInteractionEnabled=YES;
                
                [sizeLabel bk_whenTapped:^{
                    scpos=j;
                    AddColorViewController *vc=[[AddColorViewController alloc] init];
                    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                    vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
                    self.definesPresentationContext = YES;
                    vc.delegate=self;
                    vc.isRadios=YES;
                    vc.selectList=colorList;
                    [self presentViewController:vc animated:YES completion:nil];
                }];
                
                [sizeLabel sizeToFit];
                sizeLabel.frame=CGRectMake(cy, 5, sizeLabel.frame.size.width+10, 30);
                cy=CGRectGetMaxX(sizeLabel.frame)+10;
                [_colorView addSubview:sizeLabel];
                j++;
            }
            
            
            for (NSLayoutConstraint *ct in  [_colorView constraints]) {
                if(ct.firstAttribute==NSLayoutAttributeWidth)
                {
                    ct.constant=cy;
                }
            }
            
            
            colorList=selectDatas;
            [self reloadNumber];
            break;
            
        default:
            break;
    }
}

-(void)didSelectData:(ChooseType)type andData:(id)selectData
{
    
    if(type==ChooseTypeCategory)
    {
        category=(CategoryModel*)selectData;
        [_categoryBtn setTitle:category.categoryName forState:UIControlStateNormal];
        [popover dismissPopoverAnimated:YES];
    }
    else if(type==ChooseTypeSize)
    {
        NSString *size=(NSString*)selectData;
        NSMutableArray *slist=[[NSMutableArray alloc] initWithArray:sizeList];
        [slist replaceObjectAtIndex:scpos withObject:size];
       [self didSelectDatas:type andData:slist];
    }
    else  if(type==ChooseTypeColor)
    {
        NSString *color=(NSString*)selectData;
        
        NSMutableArray *clist=[[NSMutableArray alloc] initWithArray:colorList];
        [clist replaceObjectAtIndex:scpos withObject:color];
        [self didSelectDatas:type andData:clist];
    }
    
}


-(void) reloadNumber
{
    [_colorSizeView setColorList:colorList];
    [_colorSizeView setSizeList:sizeList];
    [_colorSizeView setDataList:[AppService getProductNumListById:product.productId andColorList:colorList andSizeList:sizeList]];
    
}
@end
